package com.yuan.controller;

import com.yuan.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * websocket控制器
 */
@Controller
@RequestMapping("/socket")
@Slf4j
public class WebSocketController {
    /**
     * 页面请求
     *
     * @param userId
     * @return
     */
    @RequestMapping("/index/{userId}")
    public ModelAndView socket(@PathVariable String userId) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/index");
        mv.addObject("userId", userId);
        return mv;
    }

    @ResponseBody
    @GetMapping("/sendMessage/{userId}")
    public Map sendMsg(@PathVariable String userId, String message) {
        Map<String, Object> map = new HashMap<>();
        try {
            WebSocketService.sendMessage(message, userId);
            map.put("code", userId);
            map.put("msg", message);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return map;
    }
}
